package com.thlws.rabbitmq.pubsub;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

/***
 * 发布订阅模式
 * BuiltinExchangeType.FANOUT
 * Producer数据都发往Exchange,消费端与Exchange绑定后，多个消费端都可以收到消息.
 * 注意此时 routingKey 为空
 */
public class Consumer {
	
	private static final String EXCHANGE_NAME = "logs";

	public static void main(String[] args) throws Exception{
		
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("116.228.212.36");
		factory.setUsername("hanley");
		factory.setPassword("hanley");
		factory.setVirtualHost("/test");
		
	    Connection connection = factory.newConnection();
	    Channel channel = connection.createChannel();

	    //BuiltinExchangeType.FANOUT 表示发布订阅模式
	    channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
	    //发布订阅模式不关心queueName,这里随机生成一个
	    String queueName = channel.queueDeclare().getQueue();
	    System.out.println("queueName="+queueName);//amq.gen-js-9Sjz_kF47BhIj_E389w
	    channel.queueBind(queueName, EXCHANGE_NAME, "");

	    DeliverCallback deliverCallback = (consumerTag, delivery) -> {
	        String message = new String(delivery.getBody(), "UTF-8");
	        System.out.println(" [x] Received '" + message + "'");
	        
	        //手动确认消息时需要
//	        long deliveryTag = delivery.getEnvelope().getDeliveryTag();
//	        channel.basicAck(deliveryTag, false);
	    };
	    channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });

	   
	    
	}

}
